package com.ceba.test.modules.storage.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.ceba.base.utils.IDSDateUtils;
import com.ceba.cebautils.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;

import com.ceba.test.base.configs.CebaConfig;
import com.ceba.test.modules.storage.entity.GStorageAddress;

import abc.ID;
import abc.data.DataRow;
import abc.data.DataTable;
import abc.data.Sql;
import abc.data.SqlSessionManager;
import abc.data.dataSource.SqlDataSource;
import abc.data.store.IStore;
import abc.data.store.StoreManager;
import abc.object.IObject;
import abc.object.XObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author Administrator
 *
 */
public class GStorageAddressDao {
	private static Logger logger = LoggerFactory.getLogger(GStorageAddressDao.class);
	
	private String tableName="g_storage_address";
	/**
	 * 查询
	 * @param // Id
	 * @return
	 */
	public GStorageAddress sreach(String id){
		Sql sql = new Sql("select * from "+tableName+" where ID=?");
		sql.addParameter(id);
		DataTable dataTable=SqlSessionManager.getDataTable(sql);
		if(dataTable.getRowCount() > 0){
			DataRow row=dataTable.getRow(0);
			GStorageAddress gStorageAddress=rowToGStorageAddress(row);
			return gStorageAddress;
		}

		logger.debug("没有找到存储地址记录。id=" + id);
		return null;
	}
	
	/**
	 * 将一行表数转换为 GStorageAddress 对象
	 * @param row
	 * @return
	 */
	private GStorageAddress rowToGStorageAddress(DataRow row){
		if(row == null){
			logger.error("存储地址转换失败。");
			return null;
		}
		GStorageAddress gStorageAddress=new GStorageAddress();
		gStorageAddress.setId(row.getString("ID"));
		gStorageAddress.setName(row.getString("NAME"));
		gStorageAddress.setFilter(row.getString("FILTER"));
		gStorageAddress.setPath(row.getString("PATH"));
		gStorageAddress.setCapacity(row.getLong("CAPACITY"));
		gStorageAddress.setActualSize(row.getLong("ACTUAL_SIZE"));
		gStorageAddress.setRest(row.getLong("REST"));
		gStorageAddress.setStatus(row.getString("STATUS"));
		gStorageAddress.setCopyFlag(row.getString("COPY_FLAG"));
		gStorageAddress.setCreateUser(row.getString("CREATE_USER"));
		gStorageAddress.setCreateTime(IDSDateUtils.dataToStr(row.getDate("CREATE_TIME"), DateUtil.YYYY_MM_DD_HH_MM));
		gStorageAddress.setUpdateUser(row.getString("UPDATE_USER"));
		gStorageAddress.setUpdateTime(IDSDateUtils.dataToStr(row.getDate("UPDATE_TIME"), DateUtil.YYYY_MM_DD_HH_MM));
		gStorageAddress.setSpare1(row.getString("SPARE1"));
		gStorageAddress.setSpare2(row.getString("SPARE2"));
		gStorageAddress.setSpare3(row.getString("SPARE3"));
		return gStorageAddress;
	}
	
	/**
	 * 编辑
	 * @param // GStorageAddress 表路径对象
	 * @return
	 */
	public boolean edit(GStorageAddress gStorageAddress){
		IStore store = StoreManager.create(tableName);
		IObject object = new XObject(tableName);
		object.put("ID",gStorageAddress.getId());
		
		if(StringUtils.isNotEmpty(gStorageAddress.getName())){
			object.put("NAME",gStorageAddress.getName());
		}
		
		if(StringUtils.isNotEmpty(gStorageAddress.getFilter())){
			object.put("FILTER",gStorageAddress.getFilter());
		}
		if(StringUtils.isNotEmpty(gStorageAddress.getPath())){
			object.put("PATH",gStorageAddress.getPath());
		}
		if(gStorageAddress.getCapacity() >= 0){
			object.put("CAPACITY",gStorageAddress.getCapacity());
		}
		if(gStorageAddress.getActualSize() >= 0){
			object.put("ACTUAL_SIZE",gStorageAddress.getActualSize());
		}
		if(gStorageAddress.getRest() >= 0){
			object.put("REST",gStorageAddress.getRest());
		}
		if(StringUtils.isNotEmpty(gStorageAddress.getStatus())){
			object.put("STATUS",gStorageAddress.getStatus());
		}
		if(StringUtils.isNotEmpty(gStorageAddress.getCopyFlag())){
			object.put("COPY_FLAG",gStorageAddress.getCopyFlag());
		}
		if(StringUtils.isNotEmpty(gStorageAddress.getCreateUser())){
			object.put("CREATE_USER",gStorageAddress.getCreateUser());
		}
		if(StringUtils.isNotEmpty(gStorageAddress.getCreateTime())){
			object.put("CREATE_TIME",gStorageAddress.getCreateTime());
		}
		if(StringUtils.isNotEmpty(gStorageAddress.getUpdateUser())){
			object.put("UPDATE_USER",gStorageAddress.getUpdateUser());
		}
		if(StringUtils.isNotEmpty(gStorageAddress.getUpdateTime())){
			object.put("UPDATE_TIME",gStorageAddress.getUpdateTime());
		}
		if(StringUtils.isNotEmpty(gStorageAddress.getSpare1())){
			object.put("SPARE1",gStorageAddress.getSpare1());
		}
		if(StringUtils.isNotEmpty(gStorageAddress.getSpare2())){
			object.put("SPARE2",gStorageAddress.getSpare2());
		}
		if(StringUtils.isNotEmpty(gStorageAddress.getSpare3())){
			object.put("SPARE3",gStorageAddress.getSpare3());
		}
		if(store.update(object)>0){
			return true;
		}

		logger.error("存储地址更新失败。object=" + object.toText());
		return false;
	}

	/**
	 * 编辑 
	 * @param //GStorageAddress 表路径对象
	 * @return
	 */
	public boolean editAll(GStorageAddress gStorageAddress){
		IStore store = StoreManager.create(tableName);
		IObject object = new XObject(tableName);
		object.put("ID",gStorageAddress.getId());
		object.put("NAME",gStorageAddress.getName());
		object.put("FILTER",gStorageAddress.getFilter());
		object.put("PATH",gStorageAddress.getPath());
		object.put("CAPACITY",gStorageAddress.getCapacity());
		object.put("ACTUAL_SIZE",gStorageAddress.getActualSize());
		object.put("REST",gStorageAddress.getRest());
		object.put("STATUS",gStorageAddress.getStatus());
		object.put("COPY_FLAG",gStorageAddress.getCopyFlag());
		object.put("CREATE_USER",gStorageAddress.getCreateUser());
		object.put("CREATE_TIME",gStorageAddress.getCreateTime());
		object.put("UPDATE_USER",gStorageAddress.getUpdateUser());
		object.put("UPDATE_TIME",gStorageAddress.getUpdateTime());
		object.put("SPARE1",gStorageAddress.getSpare1());
		object.put("SPARE2",gStorageAddress.getSpare2());
		object.put("SPARE3",gStorageAddress.getSpare3());
		if(store.update(object)>0){
			return true;
		}

		logger.error("editAll:存储地址更新失败。object=" + object.toText());
		return false;
	}
	
	/**
	 * 更新每一项
	 * @param id
	 * @param item
	 * @param value
	 * @return
	 */
	private boolean updateItem(String id,String item,String value){
		IStore store = StoreManager.create(tableName);
		XObject object = new XObject("ID", id);
		object.put(item, value);
		object.put("UPDATE_TIME",DateUtil.getNowTime(null));
		long count=store.update(object);
		if(count > 0){
			return true;
		}

		logger.error("updateItem:存储地址更新列失败。object=" + object.toText());
		return false;
	}

	/**
	 * 更新路径
	 * @param id
	 * @param value
	 * @return
	 */
	public boolean updatePath(String id,String value){
		IStore store = StoreManager.create(tableName);
		XObject object = new XObject("ID", id);
		object.put("PATH", value);
		long count=store.update(object);
		if(count > 0){
			return true;
		}

		logger.error("updatePath:存储地址更新路径失败。object=" + object.toText());
		return false;
	}
	
	/**
	 * 添加
	 * @param //GStorageAddress 表路径对象
	 * @return
	 */
	public boolean add(GStorageAddress gStorageAddress){
		IStore store = StoreManager.create(tableName);
		String id=gStorageAddress.getId();
		if(StringUtils.isEmpty(id)){
			id=ID.getGuid();
		}
		XObject object = new XObject("ID", id);
		object.put("NAME", gStorageAddress.getName());
		object.put("FILTER", gStorageAddress.getFilter());
		object.put("PATH", gStorageAddress.getPath());
		object.put("CAPACITY", gStorageAddress.getCapacity());
		object.put("ACTUAL_SIZE", gStorageAddress.getActualSize());
		object.put("REST", gStorageAddress.getRest());
		object.put("STATUS", gStorageAddress.getStatus());
		object.put("COPY_FLAG", gStorageAddress.getCopyFlag());
		
		if(StringUtils.isEmpty(gStorageAddress.getCreateUser())){
			object.put("CREATE_USER", CebaConfig.ANDMIN_USER_ID);
		}else{
			object.put("CREATE_USER", gStorageAddress.getCreateUser());
		}
		
		if(gStorageAddress.getCreateTime() == null){
			object.put("CREATE_TIME",DateUtil.getNowTime(null));
		}else{
			object.put("CREATE_TIME", gStorageAddress.getCreateTime());
		}
		
		
		if(StringUtils.isEmpty(gStorageAddress.getCreateUser())){
			object.put("UPDATE_USER", CebaConfig.ANDMIN_USER_ID);
		}else{
			object.put("UPDATE_USER", gStorageAddress.getUpdateUser());
		}
		
		if(gStorageAddress.getUpdateTime() == null){
			object.put("UPDATE_TIME",DateUtil.getNowTime(null));
		}else{
			object.put("UPDATE_TIME", gStorageAddress.getUpdateTime());
		}
		
		
		object.put("SPARE1", gStorageAddress.getSpare1());
		object.put("SPARE2", gStorageAddress.getSpare2());//默认为待审核
		object.put("SPARE3", gStorageAddress.getSpare3());
		if (store.insert(object) > 0) {
			return true;
		}

		logger.error("updatePath:存储地址添加失败。object=" + object.toText());
		return false;
	}
	
	/**
	 * 查询
	 * @param gStorageAddress
	 * @param dic
	 * @return
	 */
	public JSONObject list(GStorageAddress gStorageAddress, Map<String, Object> dic) {
		Sql sql=new Sql("select * from "+tableName+" where NAME LIKE ? OR PATH LIKE ? ORDER BY UPDATE_TIME");
		if(StringUtils.isNotEmpty(gStorageAddress.getSreachContent())){
			sql.addParameter("%"+gStorageAddress.getSreachContent()+"%"); 
			sql.addParameter("%"+gStorageAddress.getSreachContent()+"%"); 
		}else{
			sql=new Sql("select * from "+tableName+" ORDER BY UPDATE_TIME");
		}
		
		SqlDataSource dataSource = new SqlDataSource();
		dataSource.getSelectCommands().add(sql);
		DataTable dataTable = dataSource.query(0, dic);
		if(dataTable !=null){
			JSONObject object = dataTable.toJSONObject();
			return object;
		}
		return null;
	}
	
	public List<GStorageAddress> sreachAll(){
		Sql sql=new Sql("select * from "+tableName);
		DataTable dataTable=SqlSessionManager.getDataTable(sql);
		if(dataTable != null && dataTable.getRowCount() > 0){
			List<GStorageAddress> addresseList=new ArrayList<>();
			for(DataRow row:dataTable.getRows()){
				addresseList.add(toGStorageAddress(row));
			}
			return addresseList;
		}
		return null;
	}
	
	
	private GStorageAddress toGStorageAddress(DataRow row){
		if(row != null){
			GStorageAddress gStorageAddress=new GStorageAddress();
			gStorageAddress.setId(row.getString("ID"));
			gStorageAddress.setName(row.getString("NAME"));
			gStorageAddress.setFilter(row.getString("FILTER"));
			gStorageAddress.setPath(row.getString("PATH"));
			gStorageAddress.setCapacity(row.getLong("CAPACITY"));
			gStorageAddress.setActualSize(row.getLong("ACTUAL_SIZE"));
			gStorageAddress.setRest(row.getLong("REST"));
			gStorageAddress.setStatus(row.getString("STATUS"));
			gStorageAddress.setCopyFlag(row.getString("COPY_FLAG"));
			gStorageAddress.setCreateUser(row.getString("CREATE_USER"));
			gStorageAddress.setCreateTime(row.getString("CREATE_TIME"));
			gStorageAddress.setUpdateUser(row.getString("UPDATE_USER"));
			gStorageAddress.setUpdateTime(row.getString("UPDATE_TIME"));
			gStorageAddress.setSpare1(row.getString("SPARE1"));
			gStorageAddress.setSpare2(row.getString("SPARE2"));
			gStorageAddress.setSpare3(row.getString("SPARE3"));
			return gStorageAddress;
		}
		return null;
	}

	/**
	 * 删除
	 * @param id
	 * @return
	 */
	public boolean delete(String id) {
		Sql sql=new Sql("delete from "+tableName+" where ID = ?");
		sql.addParameter("ID", id);
		return SqlSessionManager.execute(sql);
	}

	public long totalCount() {
		Sql sql=new Sql("select ID as count from "+tableName);
		return SqlSessionManager.getCount(sql);
	}

	public long sreachPath(String id,String path,String fileName) {
		//path 包含了  PATH（表） 或  PATH 包含了  path 都会被查询出来
		Sql sql=new Sql("select ID as count from "+tableName+" where (PATH LIKE ? || instr(?,PATH) || NAME = ?) and ID != ?");
		String pathStr=StringUtils.replace(path, "\\", "/");
		sql.addParameter(StringUtils.replace(pathStr,"/", "\\\\")+"%");
		sql.addParameter(StringUtils.replace(pathStr,"/", "\\"));
		sql.addParameter(fileName);
		sql.addParameter(id);
		return SqlSessionManager.getCount(sql);
	}
	
	public void editCopyFlag(String id, String code) {
		updateItem(id,"COPY_FLAG",code);
	}
	public void editStatus(String id, String code) {
		updateItem(id,"STATUS",code);
	}
	
	
	
	/**
	 * 随机附件
	 * 
	 * select (select VIRTUAL_PATH from ids_g_file where ID=gf.FILE_ID) as VIRTUAL_PATH from IDS_WF_REPORT p,IDS_WF_USER_INSTANCE i,ids_wf_user_file f,IDS_WF_USER_FILE_ATTACH a,ids_g_user_file gf  
				where p.STORAGE_ADDRESS_ID = '55555555555555555555555555555555' and p.ID = i.REPORT_ID and i.ID=f.WF_USER_INSTANCE_ID and f.ID =a.ATTACH_FILE_ID and a.USER_FILE_ID=gf.ID order by rand() limit 10
	 * 
	 * @param id
	 * @return
	 */
	public List<String> randAttachFile(String id) {
		String sql="select (select gf.VIRTUAL_PATH from ids_g_file gf,ids_g_user_file gu where gu.ID=a.ATTACH_FILE_ID and gf.ID=gu.FILE_ID) as VIRTUAL_PATH from IDS_WF_REPORT p,IDS_WF_USER_INSTANCE i,ids_wf_user_file f,IDS_WF_USER_FILE_ATTACH a"+
				" where p.STORAGE_ADDRESS_ID = ? and p.ID = i.REPORT_ID and i.ID=f.WF_USER_INSTANCE_ID  and f.ID =a.USER_FILE_ID order by rand() limit 10";	
		return randFile(sql,id);
	}
	/**
	 * 随机签名文件
	 * @param id
	 * @return
	 */
	public List<String> randSignFile(String id) {
		String sql="select (select VIRTUAL_PATH from ids_g_file where ID=r.FILE_ID) as VIRTUAL_PATH from ids_wf_sign_record r,ids_wf_report p where r.REPORT_ID=p.ID and p.STORAGE_ADDRESS_ID = ? order by rand() limit 10";
		return randFile(sql,id);
	}
	/**
	 * 随机主文件
	 * select (select VIRTUAL_PATH from ids_g_file where ID=ORIENT_FILE_ID) as VIRTUAL_PATH from ids_wf_report where STORAGE_ADDRESS_ID = '55555555555555555555555555555555' order by rand() limit 10
	 * @param id 
	 * @return
	 */
	public List<String> randMailFile(String id) {
		String sql="select (select VIRTUAL_PATH from ids_g_file where ID=ORIENT_FILE_ID) as VIRTUAL_PATH from ids_wf_report where STORAGE_ADDRESS_ID = ? order by rand() limit 10";
		return randFile(sql,id);	
	}
	/**
	 * 随机签章
	 * select FILE_PATH as VIRTUAL_PATH from ids_g_stamp where STORAGE_ADDRESS_ID ='55555555555555555555555555555555' order by rand() limit 10
	 * @param id
	 * @return
	 */
	public List<String> randStampFile(String id) {
		String sql="select FILE_PATH as VIRTUAL_PATH from ids_g_stamp where STORAGE_ADDRESS_ID =? order by rand() limit 10";
		return randFile(sql,id);	
	}
	/**
	 * 随机模板文件
	 * select VIRTUAL_PATH from ids_g_templates_word  order by rand() limit 10
	 * @param id
	 * @return
	 */
	public List<String> randTemplatesFile(String id) {
		String sql="select VIRTUAL_PATH from ids_g_templates_word  order by rand() limit 10";
		return randFile(sql,null);
	}
	
	private List<String> randFile(String sqlStr,String id){
		List<String> pathList=new ArrayList<>();
		Sql sql=new Sql(sqlStr);
		if(StringUtils.isNotBlank(id)){
			sql.addParameter(id);
		}
		DataTable dataTable=SqlSessionManager.getDataTable(sql);
		
		if(dataTable != null && dataTable.getRowCount() > 0){
			for(DataRow row:dataTable.getRows()){
				String virtual_path=row.getString("VIRTUAL_PATH");
				if(StringUtils.isNotEmpty(virtual_path)){
					pathList.add(virtual_path);
				}
			}
			return pathList;
		}
		return null;
	}

	/**
	 * 查询出已拷贝状态的存储地址
	 * @return
	 */
	public GStorageAddress searchCopiedAddress() {
		Sql sql=new Sql("select * from "+tableName+" where COPY_FLAG='2' ORDER BY CREATE_TIME ASC limit 1");
		DataTable dataTable=SqlSessionManager.getDataTable(sql);
		if(dataTable != null && dataTable.getRowCount() > 0){
			DataRow row=dataTable.getRow(0);
			return toGStorageAddress(row);
		}
		return null;
	}
}
